package com.midea.thread;
//生产者消费者问题
public class TestProducerConsumer {
    public static void main(String[] args) {
        MyStack stack = new MyStack();
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                for (char c = 'A';c<= 'Z';c++){
                    stack.push(c+"");
                }

            }
        };
        Runnable task2 = new Runnable() {
            @Override
            public void run() {
                for (int i =1;i<=26;i++){
                    stack.pop();
                }
            }
        };

        new Thread(task1).start();
        //new Thread(task1).start();
        new Thread(task2).start();
        //new Thread(task2).start();
    }
}
//用数组实现一个栈,后进先出
class MyStack{
    String[] data = {"","","","","",""};
    int index;
    public synchronized void push(String s){
        //避免出现两个生产者，所以要用while，不能用if；
        while (data.length==index){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print(s+"pushed   ");
        data[index] = s;
        index++;
        print();
        this.notifyAll();//通知消费者
    }

    public synchronized void pop(){
        //避免出现两个消费者，所以要用while，不能用if；
        while (index==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        index--;
        String o = data[index];
        data[index] = "";
        System.out.print(o+"poped   ");
        print();
        this.notifyAll();//通知生产者
    }
    public void print(){
        for (int i = 0;i<data.length;i++){
            System.out.print(data[i]+" ");
        }
        System.out.println();
    }
}
